package com.meiwenhui.sishuwujing;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.meiwenhui.sishuwujing.adapter.BooksAdapter;
import com.meiwenhui.sishuwujing.entities.Book;
import com.meiwenhui.sishuwujing.entities.Catalogue;
import com.meiwenhui.sishuwujing.util.HttpUtil;
import com.meiwenhui.sishuwujing.view.LoadingProgressDialog;
import com.meiwenhui.sishuwujing.view.NoScrollBarGridView;
import com.orm.androrm.Filter;

public class MainActivity extends BaseActivity {

	private final static String TAG = "MainActivity";

	private ListView mListView;

	private LoadingProgressDialog loadingProgressDialog = null;

	private void initView() {
		mListView = (ListView) findViewById(R.id.books);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();

		SyncCategories syncCategories = new SyncCategories();
		syncCategories.execute();

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());
	}

	private void startProgressDialog() {
		if (loadingProgressDialog == null) {
			loadingProgressDialog = LoadingProgressDialog.createDialog(this);
			loadingProgressDialog.setMessage("正在加载中...");
		}
		loadingProgressDialog.show();
	}

	private void stopProgressDialog() {
		if (loadingProgressDialog != null) {
			loadingProgressDialog.dismiss();
			loadingProgressDialog = null;
		}
	}

	class BookListViewAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater inflater;
		private List<Categories4Books> c4bs;

		public BookListViewAdapter(Context context, List<Categories4Books> c4bs) {
			this.context = context;
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.c4bs = c4bs;
		}

		@Override
		public int getCount() {
			return c4bs.size();
		}

		@Override
		public Object getItem(int position) {
			return c4bs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView txtView = null;
			NoScrollBarGridView gridView = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.activity_main_gridview, null);
				gridView = (NoScrollBarGridView) convertView.findViewById(R.id.gridview);
				gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						Intent intent = new Intent(MainActivity.this, ChapterActivity.class);
						Book book = (Book) view.getTag();
						intent.putExtra("bookId", book.getBookId());
						intent.putExtra("bookName", book.getName());
						intent.putExtra("author", book.getAuthor());
						startActivity(intent);
					}
				});
			}
			txtView = (TextView) convertView.findViewById(R.id.txtView);

			String key = c4bs.get(position).getCategory().getName();

			txtView.setText(key);

			List<Book> bks = c4bs.get(position).getBooks();

			gridView.setAdapter(new BooksAdapter(context, bks));

			return convertView;
		}
	}

	class Categories4Books {
		private Catalogue category;
		private List<Book> books;

		public Catalogue getCategory() {
			return category;
		}

		public void setCategory(Catalogue category) {
			this.category = category;
		}

		public List<Book> getBooks() {
			return books;
		}

		public void setBooks(List<Book> books) {
			this.books = books;
		}
	}

	private class SyncCategories extends AsyncTask<Void, Integer, List<Categories4Books>> {

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "开始获取数据 ... ");
			startProgressDialog();
		}

		@Override
		protected List<Categories4Books> doInBackground(Void... params) {
			List<Categories4Books> categories4Books = new ArrayList<MainActivity.Categories4Books>(0);
			List<Catalogue> categories = Catalogue.objects(MainActivity.this, Catalogue.class).toList();

			if (categories.size() != 0) {
				categories4Books = new ArrayList<MainActivity.Categories4Books>();
				for (Catalogue category : categories) {
					Categories4Books c4b = new Categories4Books();
					c4b.setCategory(category);
					Filter filter = new Filter();
					filter.is("catalogueId", category.getCatalogueId());
					List<Book> books = Book.objects(MainActivity.this, Book.class).filter(filter).toList();
					c4b.setBooks(books);
					categories4Books.add(c4b);
				}
			} else {
				Log.i(TAG, "连网查询");
				try {
					List<Catalogue> catalogues = HttpUtil.getCategories();
					for (Catalogue catalogue : catalogues) {
						List<Book> books = HttpUtil.getBooks(catalogue.getCatalogueId());
						Categories4Books c4b = new Categories4Books();
						c4b.setCategory(catalogue);
						c4b.setBooks(books);
						categories4Books.add(c4b);
					}
				} catch (ClientProtocolException e2) {
					Log.e(TAG, e2.getLocalizedMessage(), e2);
				} catch (IOException e2) {
					Log.e(TAG, e2.getLocalizedMessage(), e2);
				} catch (JSONException e2) {
					Log.e(TAG, e2.getLocalizedMessage(), e2);
				}
			}
			return categories4Books;
		}

		// onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... progresses) {
			Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
		}

		// onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(List<Categories4Books> c4bs) {
			Log.i(TAG, "开始填充组件 ... ");
			mListView.setAdapter(new BookListViewAdapter(MainActivity.this, c4bs));
			stopProgressDialog();
		}

		// onCancelled方法用于在取消执行中的任务时更改UI
		@Override
		protected void onCancelled() {
			Log.i(TAG, "onCancelled() called");
		}

	}
}
